import {
  getWorkOrderInforByPage,
  addWorkOrderInfor,
  updateWorkOrderInfor,
  delWorkOrderInfor,
  getWorkOrderInfoBarCode,
  getPdfs,
} from '@/services/material/workOrderInfor';
import { getProductTypeList } from '@/services/templateMaintain/inspectionTemplate';
import { Ellipsis } from '@/components/Ellipsis';
import { PlusOutlined, LogoutOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Tabs, Modal, Table, Row, Col, message } from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import type { ColumnsType } from 'antd/es/table';
import { tableSearchPublicConfig } from '@/utils/filterUtils';

const WorkOrderInfor: React.FC<{}> = () => {
  const actionRef = useRef<ActionType>();
  const ref = useRef(null);
  const [theselectedRowKeys, settheSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectdata, setselectdata] = useState([]);

  const [selections, setSelections] = useState([]);
  const [selectionsOnly, setSelectionsOnly] = useState([]);

  //选中selection中的序号
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    settheSelectedRowKeys(newSelectedRowKeys);
    console.log('已选择', newSelectedRowKeys);
  };

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '项目编号',
      dataIndex: 'projectCode',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      width: 120,

      // defaultSortOrder: 'descend', //默认降序，升序用ascend
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      width: 150,
    },
    {
      title: '当前批次',
      dataIndex: 'currentBatch',
      align: 'center',
      sorter: true,
      // render: (text, record, _, action) => {
      //   return record.currentBatch + '/' + record.batchCount;
      // },
      search: false,
      width: 80,
    },
    {
      title: '柜体类型',
      dataIndex: 'productType',
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
      valueType: 'select',
      request: async () => {
        const getproduct = await getProductTypeList(null);
        const productOptionContract: any[] = [];
        getproduct.data.map((item: any, index: any) => {
          productOptionContract.push({ value: item, label: item });
        });
        return productOptionContract;
      },
      width: 120,
    },
    {
      title: '工单编号',
      dataIndex: 'wo',
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      width: 260,
    },
    // {
    //   title: '柜体编号',
    //   dataIndex: 'batchProductCode',
    //  align: 'center',sorter: true,
    // },
    // {
    //   title: '当前批次',
    //   dataIndex: 'currentBatch',
    //  align: 'center',sorter: true,
    // },
    // {
    //   title: '柜体工单释放时间',
    //   dataIndex: 'releaseTime',
    //   width: 150,
    //  align: 'center',sorter: true,
    // },
    {
      title: '工单描述',
      dataIndex: 'woDesc',
      align: 'center',
      sorter: true,
      hideInTable: true, //后端API没有传，这里隐藏掉
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '工单计划释放标识',
      dataIndex: 'releaseFlag', // 0 we 1-已释放
      width: 150,
      align: 'center',
      sorter: true,

      render: (text, record, _, action) => {
        return <div>{record.releaseFlag == 1 ? '已释放' : '未释放'}</div>;
      },
      valueType: 'select',
      request: async () => [
        { value: 1, label: '已释放' },
        { value: 0, label: '未释放' },
      ],
    },
    // {
    //   title: '柜体工单排程状态',
    //   dataIndex: 'scheduledFlag', // 0- 未排程 1-自动排程 2-手动排程
    //   width: 150,
    //  align: 'center',sorter: true,
    //   render: (text) => {
    //     return <div>{statusArray[text]}</div>;
    //   },
    // },
    // {
    //   title: '创建日期', //表头显示的名称
    //   search: false,
    //   width: 200,
    //   dataIndex: 'createTime',
    //  align: 'center',sorter: true,
    // },
    // {
    //   title: '创建人', //表头显示的名称
    //   search: false,
    //   dataIndex: 'createName',
    //  align: 'center',sorter: true,
    // },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      width: 120,
      render: (text, record, _, action) => [
        <a
          key="downloadKey"
          onClick={async () => {
            const temp = new Array();
            temp.push(record.id); //放到数组中
            const res = await getPdfs(temp);
            console.log(res);
            const iframe = document.createElement('iframe'); //通过iframe进行打印机打印
            iframe.style.display = 'none';
            iframe.src = window.URL.createObjectURL(res);
            document.body.appendChild(iframe);
            iframe.contentWindow?.focus();
            iframe.contentWindow?.print();
            /*             getWorkOrderInfoBarCode({id: record.id}).then((res) => {
              const aLink = document.createElement('a');
              document.body.appendChild(aLink);
              aLink.style.display = 'none';
              aLink.href = window.URL.createObjectURL(res);
              const filename = record.wo + '条码.png';
              aLink.setAttribute('download', `${filename}`);
              aLink.click();
              document.body.removeChild(aLink);
            }); */
          }}
        >
          打印条码
        </a>,
      ],
    },
  ];

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: string[]) => {
      const temp: string[] = [];
      const tempCodeOlny: string[] = [];
      if (selectedRows !== null) {
        selectedRows.map((item) => {
          temp.push({
            wo: item.wo,
            id: item.id,
          });
          tempCodeOlny.push(item.id);
        });
      }
      setSelectionsOnly(tempCodeOlny);
      setSelections(temp);
    },
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="生产工单查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={{
          labelWidth: 125,
          ...tableSearchPublicConfig,
        }}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="download_button"
            type="primary"
            onClick={async () => {
              if (selections.length === 0) {
                message.info('请选择要打印的工单');
              } else {
                const temp = new Array(); //API只需要id，因此将id放到一个数组中
                selections.map((item) => {
                  temp.push(item.id);
                });
                console.log(temp);
                const res = await getPdfs(temp);
                console.log(res);
                const iframe = document.createElement('iframe'); //通过iframe进行打印机打印
                iframe.style.display = 'none';
                iframe.src = window.URL.createObjectURL(res);
                document.body.appendChild(iframe);
                iframe.contentWindow?.focus();
                iframe.contentWindow?.print();
                /*                 const aLink = document.createElement('a');
                document.body.appendChild(aLink);
                aLink.style.display = 'none';
                aLink.href = window.URL.createObjectURL(res);
                const filename =  '生产工单.pdf';
                aLink.setAttribute('download', `${filename}`);
                aLink.click();
                document.body.removeChild(aLink); */
                actionRef.current.clearSelected();
                /*                 selections.map(async (item) => {
                  getWorkOrderInfoBarCode(item).then((res) => {
                    console.log(item,'select');
                    const aLink = document.createElement('a');
                    document.body.appendChild(aLink);
                    aLink.style.display = 'none';
                    aLink.href = window.URL.createObjectURL(res);
                    const filename = item.wo + '条码.png';
                    aLink.setAttribute('download', `${filename}`);
                    aLink.click();
                    document.body.removeChild(aLink);
                  });
                });
                actionRef.current.clearSelected(); */
              }
            }}
          >
            批量打印
          </Button>,
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     const filters = filterTran(ref.current.getFieldsValue());
          //     exportWorkOrderInfor({
          //       current: 1,
          //       pageSize: 5000,
          //       filters: filters,
          //     }).then((res) => {
          //       const aLink = document.createElement('a');
          //       document.body.appendChild(aLink);
          //       aLink.style.display = 'none';
          //       aLink.href = window.URL.createObjectURL(res);
          //       aLink.setAttribute('download', `WorkOrderInfor.xlsx`);
          //       aLink.click();
          //       document.body.removeChild(aLink);
          //     });
          //   }}
          //   type="primary"
          // >
          //   导出
          // </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          const sorters = sortTran(sort);
          const filters = filterTranNew(params);
          const result = await getWorkOrderInforByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 1250, y: 350 }}
        // rowSelection={{ onChange: onSelectChange }}
        rowSelection={{
          selections,
          ...rowSelection,
        }}
        pagination={{
          defaultPageSize: 100,
          defaultCurrent: 1,
          pageSizeOptions: [100, 500, 1000],
          showSizeChanger: true,
        }}
      />
    </PageHeaderWrapper>
  );
};
export default WorkOrderInfor;
